package com.xique.blelock.view.AcountManager;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.xique.blelock.NetUtils.NetResult;
import com.xique.blelock.NetUtils.XqNetClient;
import com.xique.blelock.R;
import com.xique.blelock.Utils.ACache;
import com.xique.blelock.Utils.MD5Util;
import com.xique.blelock.Utils.Stringkey;
import com.xique.blelock.Utils.TimeUtil;
import com.xique.blelock.model.UserInfo;
import com.xique.blelock.view.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;


import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

//密码修改
public class Passset_Activity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "Passset_Activity";
    private Button passwardset;
//    private ImageView back1;
    private EditText iPhoneinput, MConfirm,nowpasswards;
    private String uidflag = "1";
    private String tokenflag1 = "1";

    // 获取用户新
    private UserInfo userInfo;

    @BindView(R.id.title)
    TextView title;

    @BindView(R.id.modifylayout)
    View modifylayout;

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "收到数据 uid"+uidflag+"收到数据token"+tokenflag1);

    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setpassword_activity);
        ButterKnife.bind(this);
        initview();
    }

    private void initview() {
//        back1 = findViewById(R.id.BACKER);
        nowpasswards = findViewById(R.id.nowpassward);
        passwardset = findViewById(R.id.paswwset);
        iPhoneinput = findViewById(R.id.iphoneiput);
        MConfirm = findViewById(R.id.iphonePOSSWARD);
        iPhoneinput.setOnClickListener(this);
        MConfirm.setOnClickListener(this);
        passwardset.setOnClickListener(this);
//        back1.setOnClickListener(this);

        iPhoneinput.addTextChangedListener(textWatcher);
        MConfirm.addTextChangedListener(textWatcher);
        nowpasswards.addTextChangedListener(textWatcher);
        passwardset.setEnabled(false);

        userInfo = (UserInfo) ACache.get(this).getAsObject(Stringkey.USERInfo);
        if(userInfo.getIssetPwd() == 1)
        {
            title.setText("修改密码");
        }else{
            title.setText("设置密码");
            modifylayout.setVisibility(View.GONE);
        }

    }

    @OnClick(R.id.BACKER)
    public void BackLastPage(){
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.paswwset:
                String nowpassward = nowpasswards.getText().toString();//旧密码
                String newpassward = iPhoneinput.getText().toString();//设置密码
                String Confirmpassward = MConfirm.getText().toString();//确认密码

                if ( newpassward != null && Confirmpassward != null) {
                    if (newpassward.equals(Confirmpassward)) {
                        if(userInfo.getIssetPwd() == 1)
                        {
                            Sendsetpasword();
                        }else{
                            setPassword();
                        }
                    } else {
                        Toast.makeText(this, "两次输入密码不一样", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(this, "输入密码不", Toast.LENGTH_SHORT).show();
                }

                break;

            case R.id.iphonePOSSWARD:
                break;
        }
    }

    private void setPassword() {

        String newpassward = iPhoneinput.getText().toString();//设置密码
        XqNetClient netClient = new XqNetClient();
        JSONObject jsonobject = new JSONObject();
        try {
            jsonobject.put("token", userInfo.getToken());
            jsonobject.put("uid", userInfo.getUid());
            jsonobject.put("password", MD5Util.md5(newpassward));
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e(TAG, "请求的数据："+jsonobject.toString());
        showProgressDialog();
        netClient.setPassword(jsonobject.toString()).enqueue(new Callback<NetResult>() {
            @Override
            public void onResponse(Call<NetResult> call, Response<NetResult> response) {
                hideProgressDialog();
                Log.e(TAG, "-===设置密码：" + response.body());
                if(response.body().isSuccess()){
                    showToast(Passset_Activity.this, "设置密码成功");
                    userInfo.setIssetPwd(1);
                    ACache.get(Passset_Activity.this).put(Stringkey.USERInfo, userInfo);
                    Intent intent = new Intent();
                    setResult(RESULT_OK, intent);
                    finish();
                }else{
                    showToast(Passset_Activity.this, "设置密码失败"+ response.body().getMessage());
                }


            }

            @Override
            public void onFailure(Call<NetResult> call, Throwable t) {
                t.printStackTrace();
                hideProgressDialog();
            }
        });
    }

    private void Sendsetpasword() {
        String nowpassward = nowpasswards.getText().toString();//旧密码
        String newpassward = iPhoneinput.getText().toString();//设置密码
        XqNetClient netClient = new XqNetClient();
        JSONObject jsonobject = new JSONObject();
        try {
            jsonobject.put("token", userInfo.getToken());
            jsonobject.put("uid", userInfo.getUid());
            jsonobject.put("nowPassword", MD5Util.md5(nowpassward));
            jsonobject.put("newPassword", MD5Util.md5(newpassward));
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e(TAG, "请求的数据："+jsonobject.toString());
        showProgressDialog();
        netClient.changePassword(jsonobject.toString()).enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                System.out.println("-===获取的验证码是：" + response.body());
                Log.e(TAG, "-===获取修改密码信息：" + response.body());
                String code = "1";
                try {
                    JSONObject jsonObject1 = new JSONObject(response.body());
                    code = jsonObject1.getString("message");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (code.equals("成功")) {//如果成功就跳转到主界面
                    ACache.get(Passset_Activity.this).clear();
                    Toast.makeText(Passset_Activity.this, "密码已重新设置，需重新登录", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(Passset_Activity.this, Login_Activity.class);
                    startActivity(intent);
                    finish();
                }else{
                    showToast(Passset_Activity.this,code);
                }
                hideProgressDialog();
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                t.printStackTrace();
                hideProgressDialog();
            }
        });
    }

    private TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {

            if(userInfo.getIssetPwd() == 1)
            {
                if( nowpasswards.getText().length()>= 6 && (iPhoneinput.getText().length()>=6)
                        && (MConfirm.getText().length()>=6)){

                    passwardset.setEnabled(true);
                }else{
                    passwardset.setEnabled(false);
                }
            }else{
                if( (iPhoneinput.getText().length()>=6)
                        && (MConfirm.getText().length()>=6)){

                    passwardset.setEnabled(true);
                }else{
                    passwardset.setEnabled(false);
                }
            }

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

        @Override
        public void afterTextChanged(Editable s) {  }
    };
}
